package com.biz.primus.service.push.service;

import com.alibaba.fastjson.JSON;
import com.biz.primus.base.enums.push.NotifyPlatform;
import com.biz.primus.base.vo.push.Notification;
import com.biz.primus.service.push.service.interfaces.IPusher;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

/**
 * @author david-liu
 */
@Component
@Slf4j
@Setter
public class PushMessageConsumer implements MessageListener {

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    private JPusher jPusher;

    @Autowired
    private MIPusher miPusher;

    @Override
    public void onMessage(Message message) {
        final Notification notification = JSON.parseObject(new String(message.getBody()), Notification.class);
        threadPoolTaskExecutor.execute(() -> {
            try {
                IPusher pusher;
                if (notification.getPlatform().equals(NotifyPlatform.MI)) {
                    pusher = PushMessageConsumer.this.miPusher;
                } else {
                    pusher = PushMessageConsumer.this.jPusher;
                }
                pusher.push(notification);
            } catch (Exception e) {
                log.warn("Got exception when push notice.", e);
            }
        });
    }
}
